package cn.bdqn.pn.controller.schedule;

import cn.bdqn.pn.pojo.base.City;
import cn.bdqn.pn.pojo.base.Img;
import cn.bdqn.pn.pojo.schedule.Place;
import cn.bdqn.pn.pojo.user.Admin;
import cn.bdqn.pn.service.base.CityService;
import cn.bdqn.pn.service.base.ImgService;
import cn.bdqn.pn.service.schedule.PlaceService;
import cn.bdqn.pn.service.user.AdminService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 场地
 */
@Controller
@RequestMapping("place")
public class PlaceController {

    @Autowired
    private PlaceService placeService;

    @Autowired
    private ImgService imgService;

    @Autowired
    private CityService cityService;

    @Autowired
    private AdminService adminService;
    /**
     * 根据条件查询场地信息，分页,查看个人场地
     * @return
     */
    @RequestMapping(value = "/findPlaceInfo")
    @ResponseBody
    public String getByPlaceFindPlaceInfo(@Param("cityoneId") Integer cityoneId,
                                          @Param("citytwoId") Integer citytwoId,
                                          @Param("citythreeId") Integer citythreeId,
                                          @Param("status") Integer status,
                                          @Param("auditorstatus") Integer auditorstatus,
                                          @Param("pageNum") Integer pageNum,
                                          @Param("pageSize") Integer pageSize,HttpSession session){
        System.out.println("=======================================cityoneId="+cityoneId);
        System.out.println("=======================================citytwoId="+citytwoId);
        System.out.println("=======================================citythreeId="+citythreeId);
        System.out.println("=======================================status="+status);
        System.out.println("=======================================auditorstatus="+auditorstatus);
        System.out.println("=======================================pageNum000="+pageNum);
        System.out.println("=======================================pageSize="+pageSize);
        System.out.println("=====================================agentId="+((Admin) session.getAttribute("admin")).getAdminId());
        Place place=new Place();
        //从session中获取登录人的信息，拿取id
        //将id存放到对象中，进行查询，
        //如果type为person，查询自己的场地
        place.setCityoneId(cityoneId);
        place.setCitytwoId(citytwoId);
        place.setCitythreeId(citythreeId);
        place.setStatus(status);
        place.setAuditorstatus(auditorstatus);
        place.setAgentid(((Admin)session.getAttribute("admin")).getAdminId());
       /* place.setAgentid(((Admin) session.getAttribute("admin")).getAdminId());*/
        Page<Place> places=null;
        List<City> list=new ArrayList<City>();
        List<Admin> admins=new ArrayList<Admin>();
        try {
            places=placeService.getByPlaceInfoFindPlace(place,pageNum,pageSize);
            list=cityService.getAllListCityInfo();
            admins=adminService.getAllAdminInfo();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        for(Place place1 : places){
            for(City city : list){
                if(place1.getCityoneId()==city.getCityId()){
                    place1.setMore1(city.getCityName());
                }
                if(place1.getCitytwoId()==city.getCityId()){
                    place1.setMore2(city.getCityName());
                }
                if(place1.getCitythreeId()==city.getCityId()){
                    place1.setMore3(city.getCityName());
                }
            }
        }
        for(Place place1 : places){
            for(Admin admin : admins){
                if(place1.getAgentid()==admin.getAdminId()){
                    place1.setAgintName(admin.getAccount());
                }
            }
        }
        System.out.println(JSON.toJSONString(places,true));

        return JSON.toJSONString(places,true);
    }



    /**
     * 根据条件查询场地信息，分页，查看代理商的场地
     * @return
     */
    @RequestMapping(value = "/getPlaceInfo")
    public String geFindPlaceInfo(Model model,Place place, Integer pageNum,Integer pageSize,Integer status,Integer auditorstatus){
        System.out.println("=====================pageNum="+pageNum);
        System.out.println("=====================pageSize="+pageSize);
        Page<Place> places = null;
        List<City> list=new ArrayList<City>();
        List<Admin> admins=new ArrayList<Admin>();
        if(status!=null){
            place.setStatus(status);
        }
        if(auditorstatus!=null){
            place.setAuditorstatus(auditorstatus);
        }
        try {
            list=cityService.getAllListCityInfo();
            places=placeService.getByPlaceInfoFindPlace(place,pageNum,pageSize);
            admins=adminService.getAllAdminInfo();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        for(Place place1 : places){
            for(City city : list){
                if(place1.getCityoneId()==city.getCityId()){
                    place1.setMore1(city.getCityName());
                }

                if(place1.getCitytwoId()==city.getCityId()){
                    place1.setMore2(city.getCityName());
                }

                if(place1.getCitythreeId()==city.getCityId()){
                    place1.setMore3(city.getCityName());
                }
            }
        }

        for(Place place1 : places){
            for(Admin admin : admins){
                if(place1.getAgentid()==admin.getAdminId()){
                    place1.setAgintName(admin.getAccount());
                }
            }
        }
        System.out.println(JSON.toJSONString(places,true));
        System.out.println("========================getStatus="+place.getStatus());
        model.addAttribute("cityoneId",place.getCityoneId());
        model.addAttribute("citytwoId",place.getCitytwoId());
        model.addAttribute("citythreeId",place.getCitythreeId());
        model.addAttribute("status",place.getStatus());
        model.addAttribute("auditorstatus",place.getAuditorstatus());
        model.addAttribute("place",places);

        return "SeatManage";
    }




    /**
     * 添加场地信息
     * @param place
     * @return
     */
    @RequestMapping(value = "/addPlace")
    @ResponseBody
    public int addPlaceInfo(Place place,HttpSession session){
        System.out.println("================================="+place.getAddress());
        System.out.println("================================="+place.getPlacename());
        System.out.println("================================="+place.getRownum());
        System.out.println("================================="+place.getColumnnum());

        int result=0;
        try {
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String enterTime=format.format(new Date());
            place.setEntertime(enterTime);
            place.setStatus(1);
            place.setAuditorstatus(1);
            //Admin admin=(Admin)session.getAttribute("admin");
            place.setAgentid(((Admin) session.getAttribute("admin")).getAdminId());
            result=placeService.addPlaceInfo(place);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 修改场地信息
     * @param placeId
     * @param auditorstatus
     * @param auditorwhy
     * @return
     */
    @RequestMapping(value = "/upPlaceInfo")
    @ResponseBody
    public boolean upPlaceInfo(@Param("placeId")Integer placeId,@Param("auditorstatus")Integer auditorstatus,@Param("auditorwhy") String auditorwhy){
        Place place=null;
        boolean falg=false;
        try {
            place=placeService.findByPlace(placeId);
            place.setAuditorstatus(auditorstatus);
            place.setAuditorwhy(auditorwhy);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String audiTime=simpleDateFormat.format(new Date());
            place.setAuditortime(audiTime);
            falg=placeService.updatePlaceInfo(place);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(falg){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 根据场地id查询场地信息
     * @return
     */
    @RequestMapping(value = "/findByPlaceIdPlaceInfo")
    @ResponseBody
    public String findByPlaceIdPlaceInfo(@Param("placeId") Integer placeId){
        Place place=null;
        try {
             place=placeService.findByPlace(placeId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(JSON.toJSONString(place,true));
        return JSON.toJSONString(place,true);
    }

    /**
     * 根据供应商id查询场地信息
     * @return
     */
    @RequestMapping(value = "/findByAgentId")
    @ResponseBody
    public String findByagentId(){
        List<Place> placeList=null;
       try {
           /**
            * 这里应该是从session中获取登录的供应商Id
            * 这里先直接定义---------------cp 2019-08-02-23:10
            */
           placeList=placeService.findByagentId(3);
       }catch (Exception e){
           e.printStackTrace();
       }
        return JSON.toJSONString(placeList,true);
    }

    /**
     * 多图上传
     * @param files
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/MultPictareaddData")
    @ResponseBody
    public String MultPictareaddData(@RequestParam("file") MultipartFile[] files,@RequestParam("placeId") Integer placeId, HttpServletRequest request) throws IOException, SQLException {
        String imgPath="";
        if(files!=null && files.length>0){
            System.out.println("====================="+files.length+"====================="+placeId);
            for(int i=0;i<files.length;i++){
                MultipartFile file=files[i];
                //保存图片
                imgPath+=saveFile(request,file)+(i<files.length-1?"*":"");
            }
            System.out.println("================="+imgPath);
            //将图片保存到数据库中
            Img img=new Img();
            img.setImgtypeid(1);
            img.setImgurl(imgPath);
            img.setReleid(placeId);
            boolean falg=imgService.addImgInfo(img);
            if(falg){
                return JSON.toJSONString("true");
            }else{
                return JSON.toJSONString("false");
            }
        }else{
            System.out.println(files.length+"========================");
            return JSON.toJSONString("exception");
        }
    }

    private String saveFile(HttpServletRequest request,MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String name = file.getName();
        String randomUUID = UUID.randomUUID().toString();
        int index = originalFilename.lastIndexOf(".");
        String exet = originalFilename.substring(index);
        Date date = new Date();
       //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd\\HH\\mm\\ss");
        //String dateStr = sdf.format(date); // D:\\uploads\\20180824 String
        String filePath = "E:\\pn\\pnImage\\";
        System.out.println("filePath=" + filePath);
        File file2 = new File(filePath);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        //经过转换后的图片名称
        String imgPath=randomUUID+exet;
        System.out.println("图片名="+imgPath);
        filePath += "\\" + randomUUID + exet;
        System.out.println(filePath);
        file.transferTo(new File(filePath));// ctrl+1
        return imgPath;
    }


    /**
     * 根据场地id查看场地图片
     * @param placeId
     * @return
     */
    @RequestMapping("/findPlaceImg")
    @ResponseBody
    public List<String> getCommentImages(@Param("placeId") Integer placeId){
        Img img=null;
        List<String> list=new ArrayList<String>();
        System.out.println("=========================placeId="+placeId);
        try {
            img= imgService.findByImgInfo(placeId,1);
            String imgg=img.getImgurl();
            String [] a=imgg.split("\\*");
            for(int i=0;i<a.length;i++){
                list.add(a[i]);
            }
            System.out.println(a.length);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

}




